package com.chen.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

@Slf4j
public class JsonMapper {

    private static ObjectMapper objectMapper = new ObjectMapper();

    static {
        //config
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS,false);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
        objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES,true);
        objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS,true);
    }


    /**
     * 对象转String
     * @return
     */
    public static String toJson(Object obj){
        if (null == obj){
            return null;
        }
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (Exception e) {
            log.error(obj.toString(),e);
        }
        return null;
    }

    public static <T> T fromJson(String json, Class<T> clazz){
        if(StringUtils.isBlank(json)){
            return null;
        }
        try {
            return objectMapper.readValue(json,clazz);
        } catch (Exception e){
            log.error(json + "of" + clazz,e);
        }
        return null;
    }

    public static <T> T formJson(String json, TypeReference<T> typeReference){
        if(StringUtils.isBlank(json)){
            return null;
        }
        try {
            return (T) objectMapper.readValue(json,typeReference);
        } catch (Exception e){
            log.error(json + "of" + typeReference,e);
        }
        return null;
    }
}